<!-- 校验报表 -->
<template>
  <div class="equip-wrap-common">
    <div class="summary">
      <div class="s-item">
        近三个月已完成校验数量：<span>{{ verifyData.CompleteVerify }}</span>
      </div>
      <div class="s-item">
        近三个月应校验设备数量：<span>{{ verifyData.UnCompleteVerify }}</span>
      </div>
    </div>

    <px-form ref="queryRef" class="custom-form-ui equip-form" :model="queryParams" inline label-width="120px">
      <px-form-item label="年份" prop="annual">
        <px-select v-model="queryParams.annual" clearable placeholder="请选择年份">
          <px-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <!-- <px-form-item label="科室">
        <px-select v-model="queryParams.classRoom" clearable filterable>
          <px-option v-for="item in classNameList" :key="item.id" :label="item.itemName" :value="item.itemValue" />
        </px-select>
      </px-form-item> -->
      <px-form-item label="系统">
        <px-select v-model="queryParams.system" placeholder="请选择系统" clearable filterable>
          <px-option v-for="item in systemList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>

      <px-form-item label="子系统">
        <px-select v-model="queryParams.subSystem" placeholder="请选择子系统" clearable filterable>
          <px-option v-for="item in subSystemList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="设备总称">
        <px-select v-model="queryParams.deviceGeneralName" placeholder="请选择设备总称" clearable filterable>
          <px-option v-for="item in eqpCategoryList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="设备名称">
        <px-select v-model="queryParams.deviceName" placeholder="请选择设备名称" clearable filterable>
          <px-option v-for="item in eqpNameList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="设备编号">
        <px-select v-model="queryParams.deviceNumber" placeholder="请选择设备编号" clearable filterable>
          <px-option v-for="item in eqpNoList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="设备位置">
        <px-select v-model="queryParams.deviceLocation" placeholder="请选择设备位置" clearable filterable>
          <px-option v-for="item in eqpLocationList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="负责人">
        <px-select v-model="queryParams.responsiblePerson" placeholder="请选择负责人" clearable>
          <px-option v-for="item in eqpOwnerList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="设备厂家">
        <px-select v-model="queryParams.deviceMANUFACTURERS" placeholder="请选择设备厂家" clearable>
          <px-option v-for="item in eqpManufacturerList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="校验周期">
        <px-select v-model="queryParams.verifyCycle" placeholder="请选择校验周期" clearable>
          <px-option v-for="item in eqpCheckPeriodList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="上次校准日期">
        <px-date-picker v-model="queryParams.lastVerifyData" type="month" format="YYYY-MM" value-format="YYYY-MM" placeholder="请选择上次校准日期" />
      </px-form-item>
      <px-button type="primary" @click="queryTable">查询</px-button>
      <px-button @click="resetTable">重置</px-button>
    </px-form>
    <div class="equip-table-btn">
      <px-button type="primary" plain @click="showImportDialog">导入</px-button>
      &nbsp;&nbsp;
      <px-link underline type="primary" icon="download" @click="downloadTmp">下载模板</px-link>
    </div>
    <px-table :data="tableData" class="equip-table" height="calc(100vh - 380px)" border>
      <template #empty>
        <px-empty />
      </template>
      <px-table-column type="index" label="序号" width="55" align="center" />
      <px-table-column prop="classRoom" label="科室" min-width="80" />
      <px-table-column prop="system" label="系统" min-width="100" />
      <px-table-column prop="subSystem" label="子系统" min-width="100" />
      <px-table-column prop="deviceGeneralName" label="设备总称" min-width="100" />
      <px-table-column prop="deviceType" label="设备类型" min-width="100" />
      <px-table-column prop="deviceName" label="设备名称" min-width="100" />
      <px-table-column prop="deviceNumber" label="设备编号" min-width="100" />
      <px-table-column prop="deviceLocation" label="设备位置" min-width="100" />
      <px-table-column prop="responsiblePerson" label="负责人" min-width="100" />
      <px-table-column prop="deviceMANUFACTURERS" label="设备厂家" min-width="100" />
      <px-table-column prop="verifyCycle" label="校验周期" min-width="100" />
      <px-table-column prop="lastVerifyData" label="上次校准日期" min-width="100">
        <template #default="scope">
          {{ scope.row.lastVerifyData ? dayjs(scope.row.lastVerifyData).format("YYYY-MM-DD") : "" }}
        </template>
      </px-table-column>
      <px-table-column prop="nextVerifyData" label="下次校准日期" min-width="100">
        <template #default="scope">
          {{ scope.row.nextVerifyData ? dayjs(scope.row.nextVerifyData).format("YYYY-MM-DD") : "" }}
        </template>
      </px-table-column>
      <px-table-column prop="fileInfo" label="附件上传" min-width="100">
        <template #default="scope">
          <div v-if="scope.row.fileInfo">
            <px-link v-for="item in scope.row.fileInfo" :key="item.id" type="primary" target="_blank" :href="item.fileUrl">{{
              item.originalName
            }}</px-link>
          </div>
          <div v-else><px-button type="primary" plain @click="showAttachDialog(scope.row)">上传附件</px-button></div>
        </template>
      </px-table-column>
    </px-table>
    <!-- <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      class="equip-table-pagination"
      :total="total"
      @pagination="queryTable"
    /> -->
    <!-- 导入 -->
    <div v-if="fileUploadVisible">
      <FileUpload v-model:visible="fileUploadVisible" @uploadAction="fileUploadConfirm" />
    </div>
    <!-- 上传附件 -->
    <div v-if="attachUploadVisible">
      <AttachUpload v-model:visible="attachUploadVisible" @uploadAction="attachUploadConfirm" />
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MACHINE_REPORT_CHECK"
});
import { queryChildByTypeCodeAndItemValue } from "@/api/handover";
import { importReport, importCoverReport, checkRepeat, queryConditionS, queryRecordList, queryVerifyNumber, uploadAttach } from "@/api/machineCheck";
import { formatDuration } from "@/utils/pengxi";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, toRefs, ref } from "vue";
import FileUpload from "./components/fileUpload.vue";
import AttachUpload from "./components/attachUpload.vue";
import { getToken } from "@/utils/auth";
import { useRouter } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import dayjs from "dayjs";

const routerStore = useRouterStoreHook();

onMounted(() => {
  getVerifyNumber();
  getClassNameList();
  getSelectList();
  queryTable();
  // querySelectList();
});

const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
const downloadTmp = () => {
  let url = `${window.location.protocol}//${window.location.hostname}/download/校验报表模板.xlsx`;
  window.open(url);
};
const state = reactive<Record<string, any>>({
  queryParams: {
    annual: new Date().getFullYear(),
    // classRoom: routerStore.getSubject === "ALL" ? "" : routerStore.getSubject,
    pageNum: 1,
    pageSize: 20
  },
  tableData: [], // 列表数据
  total: 0, // 列表数量
  rowData: {}, // 设备编号
  dialogVisible: false, // 弹窗显示隐藏
  dialogType: "add", // 弹窗默认新增
  systemList: [],
  subSystemList: [],
  eqpCategoryList: [], //设备总称
  eqpNameList: [],
  eqpNoList: [],
  eqpLocationList: [],
  eqpOwnerList: [],
  eqpManufacturerList: [],
  eqpCheckPeriodList: [],
  fileUploadVisible: false,
  attachUploadVisible: false,
  verifyData: {},
  currentYear: new Date().getFullYear(),
  classNameList: []
});

const {
  queryParams,
  tableData,
  total,
  rowData,
  dialogVisible,
  dialogType,
  systemList,
  subSystemList,
  eqpCategoryList, //设备总称
  eqpNameList,
  eqpNoList,
  eqpLocationList,
  eqpOwnerList,
  eqpManufacturerList,
  eqpCheckPeriodList,
  fileUploadVisible,
  attachUploadVisible,
  verifyData,
  currentYear,
  classNameList
} = toRefs(state);
const yearList = ref([]);
let ym = new Date();
let tmpList = [];
for (var i = -8; i < 3; i++) {
  let y: number = ym.getFullYear();
  tmpList.push({
    label: y + i,
    value: y + i
  });
}
yearList.value = tmpList;

const getVerifyNumber = async () => {
  let res = await queryVerifyNumber();
  verifyData.value = res;
};

const showImportDialog = () => {
  fileUploadVisible.value = true;
};
const showAttachDialog = row => {
  rowData.value = row;
  attachUploadVisible.value = true;
};
const fileUploadConfirm = async data => {
  // 判断年份是否有数据
  let res = await checkRepeat({ annual: data.year });
  let fileList = data.fileList;
  let formData = new FormData();
  formData.append("annual", data.year);
  formData.append("file", fileList[0].raw);
  if (res) {
    // 有重复的
    PxMessageBox.confirm(`${data.year}已经上传过了，是否覆盖？`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        await importCoverReport(formData);
        fileUploadVisible.value = false;
        PxMessage.success("上传成功");
        queryTable();
      })
      .catch(() => {});
  } else {
    await importReport(formData);
    fileUploadVisible.value = false;
    PxMessage.success("上传成功");
    queryTable();
  }
};
const attachUploadConfirm = async fileList => {
  console.log("attach file list", fileList);
  let formData = new FormData();
  formData.append("id", rowData.value.id);
  formData.append("fileInfo", JSON.stringify(fileList));
  await uploadAttach(formData);
  attachUploadVisible.value = false;
  PxMessage.success("上传成功");
  queryTable();
};

// 搜索查询条件下拉框
const getSelectList = async () => {
  let res = await queryConditionS({ annual: currentYear.value });
  systemList.value = res.System || [];
  subSystemList.value = res.SubSystem || [];
  eqpCategoryList.value = res.DeviceGeneralName || [];
  eqpNameList.value = res.DeviceName || [];
  eqpNoList.value = res.DeviceNumber || [];
  eqpOwnerList.value = res.ResponsiblePerson || [];
  eqpManufacturerList.value = res.DeviceMANUFACTURERS || [];
  eqpLocationList.value = res.DeviceLocation || [];
  eqpCheckPeriodList.value = res.VerifyCycle || [];
};
const getClassNameList = async () => {
  const res = await queryChildByTypeCodeAndItemValue({ typeCode: "className" });
  classNameList.value = res;
};
// // 如果有厂区和科室，根据他们的值获取系统
// const visibleChangeSystem = async val => {
//   if (val) {
//     const tempSystemList = await querySystemSelect({ factoryArea: queryParams.value.facCode, className: queryParams.value.className });
//     systemList.value = tempSystemList || [];
//   } else {
//     systemList.value = [];
//   }
// };
// // 如果有总称，根据他们的值获取类型
// const handleTypeFocus = async () => {
//   const typeData = await getEquipTypeSelect({ categoryId: queryParams.value.categoryId, systemCode: queryParams.value.systemCodes });
//   typeIdList.value = typeData?.map(item => ({ label: item.name, value: item.id }));
// };
// // 如果有类型，根据他们的值获取型号
// const handleModelFocus = async () => {
//   const modelIdData = await getEquipModelSelect({ typeId: queryParams.value.typeId, categoryId: queryParams.value.categoryId });
//   modelIdList.value = modelIdData?.map(item => ({ label: item.name, value: item.id }));
// };
// // 改变厂区，清空科室和系统
// const handleFacChange = () => {
//   queryParams.value.className = "";
//   queryParams.value.systemCodes = "";
//   systemCodes.value = [];
// };
// // 改变科室，清空系统
// const handleClassChange = () => {
//   queryParams.value.systemCodes = "";
//   systemCodes.value = [];
// };
// // 改变总称，清空类型和型号
// const handleCategoryChange = () => {
//   queryParams.value.typeId = "";
//   queryParams.value.modelId = "";
// };
// // 改变类型，清空清号
// const handleTypeChange = () => {
//   queryParams.value.modelId = "";
// };
// // 点击左侧树节点，获取categoryId，查询设备列表
// const nodeClick = (e1emData, nodeData) => {
//   if (e1emData.type === "factoryArea") {
//     // 一级工厂
//     queryParams.value.facCode = e1emData.code;
//     systemCodes.value = [];
//   } else if (e1emData.type === "className") {
//     // 二级科室
//     queryParams.value.facCode = nodeData.parent.data.code;
//     queryParams.value.className = e1emData.code;
//     systemCodes.value = [];
//   } else if (e1emData.type === "systemCategory") {
//     const codes = [e1emData.code];
//     if (e1emData.children && e1emData.children.length > 0) {
//       e1emData.children.forEach(item => {
//         codes.push(item.code);
//       });
//     }
//     systemCodes.value = codes;
//   }
// };

// // 查询运行记录列表
const queryTable = async () => {
  const temp = JSON.parse(JSON.stringify(queryParams.value));
  const res = await queryRecordList({ ...temp });
  tableData.value = res || [];
  tableData.value.forEach(v => {
    if (v.fileInfo) {
      v.fileInfo = JSON.parse(v.fileInfo);
    }
  });
  // total.value = res?.total;
};
// // 重置筛选条件和运行记录列表
const resetTable = async () => {
  queryParams.value = {
    annual: new Date().getFullYear(),
    pageNum: 1,
    pageSize: 20
  };
  queryTable();
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.equip-wrap-common {
  height: calc(100vh - 177px);

  .summary {
    display: flex;
    width: 43%;
    padding: 16px 0;

    .s-item {
      flex: 1;

      span {
        font-weight: bold;
        color: #3b82f6;
      }
    }
  }

  .equip-form {
    padding-top: 0;
    margin-bottom: 8px;

    :deep(.px-form-item) {
      width: 20%;
      margin-bottom: 8px;
    }

    :deep(.px-button) {
      margin-top: -8px;
    }
  }
}
</style>
